package com.py.payment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.py.payment.dto.param.IngredientsRecordParamDto;
import com.py.payment.dto.ret.IngredientsRecordRetDto;
import com.py.payment.entity.PyIngredientsRecord;
import com.py.payment.mapper.PyIngredientsRecordMapper;
import com.py.payment.service.PyIngredientsRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.py.payment.tools.ToolsUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 成分记录表 服务实现类
 * </p>
 *
 * @author py
 * @since 2024-04-27
 */
@Service
public class PyIngredientsRecordServiceImpl extends ServiceImpl<PyIngredientsRecordMapper, PyIngredientsRecord> implements PyIngredientsRecordService {

    @Override
    public List<IngredientsRecordRetDto> getIngredientsRecordList(IngredientsRecordParamDto ingredientsRecordParamDto) {

        List<IngredientsRecordRetDto> ingredientsRecordList = this.baseMapper.getIngredientsRecordList(ingredientsRecordParamDto);

        ingredientsRecordList.forEach(item->{

            BigDecimal setValue = BigDecimal.ZERO;
            if(ToolsUtils.isNotEmpty(item.getSetValue())){
                setValue = new BigDecimal(item.getSetValue());
            }
            BigDecimal actualValue = BigDecimal.ZERO;
            if(ToolsUtils.isNotEmpty(item.getActualValue())){
                actualValue = new BigDecimal(item.getActualValue());
            }
            BigDecimal errorValue = actualValue.subtract(setValue);
            item.setErrorValue(errorValue.setScale(2,RoundingMode.HALF_UP).toPlainString());
            item.setSetValue(setValue.setScale(2,RoundingMode.HALF_UP).toPlainString());
            item.setActualValue(actualValue.setScale(2, RoundingMode.HALF_UP).toPlainString());
        });

        return ingredientsRecordList;
    }

    @Override
    public void saveIngredientsRecord(List<PyIngredientsRecord> ingredientsRecordList) {
        List<PyIngredientsRecord> ingredientsRecordListNew = new ArrayList<>();
        QueryWrapper<PyIngredientsRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("site_id",ingredientsRecordList.get(0).getSiteId());
        List<PyIngredientsRecord> hasList = this.list(queryWrapper);

        Set<String> has = new HashSet<>();
        hasList.forEach(item->{
            String k = item.getBatchId() + "_" +item.getBillId()+"_"+item.getInvestmentId();
            has.add(k);
        });

        ingredientsRecordList.forEach(item->{
            String k = item.getBatchId() + "_" +item.getBillId()+"_"+item.getInvestmentId();
            if(!has.contains(k)){
                ingredientsRecordListNew.add(item);
            }
        });

        this.saveBatch(ingredientsRecordListNew);

    }
}
